//
//  VideoViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/6.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoTableViewCell.h"

@interface VideoViewController () <UITableViewDelegate, UITableViewDataSource>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 精选杂志列表 */
@property (nonatomic, strong) UITableView * videoTableView;
/** 数据源 */
@property (nonatomic, strong) NSMutableArray * videoArr;
/** 加载页数 */
@property (nonatomic, assign) NSInteger pageIndex;
/** 视频播放器 */
@property (nonatomic, strong) MPMoviePlayerViewController * player;

@end

@implementation VideoViewController

- (MPMoviePlayerViewController *)player{
    if (!_player) {
        _player = [[MPMoviePlayerViewController alloc] init];
        _player.moviePlayer.shouldAutoplay = YES;
        _player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    }
    return _player;
}

- (NSInteger)pageIndex{
    if (!_pageIndex) {
        _pageIndex = 1;
    }
    return _pageIndex;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

- (NSMutableArray *)videoArr{
    if (!_videoArr) {
        _videoArr = [NSMutableArray array];
    }
    return _videoArr;
}

- (UITableView *)videoTableView{
    if (!_videoTableView) {
        _videoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W, SCREEN_H - 64)];
        _videoTableView.delegate = self;
        _videoTableView.dataSource = self;
        _videoTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _videoTableView.rowHeight = HeightScale(145);
        _videoTableView.tableFooterView = [UIView new];
        _videoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _videoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestVideo:)];
        _videoTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestVideo:)];
    }
    return _videoTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.videoTableView];
    
    [self.videoTableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.videoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"videoCell";
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[VideoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    
    cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.videoArr[indexPath.row][@"name"]];
    
    cell.timeLabel.text = [Tool dateConvert:[NSString stringWithFormat:@"%@", self.videoArr[indexPath.row][@"publishTime"]]];
    
    cell.descLabel.text = [NSString stringWithFormat:@"%@", self.videoArr[indexPath.row][@"summarytext"]];
    cell.authorLabel.text = [NSString stringWithFormat:@"%@", self.videoArr[indexPath.row][@"author"]];
    NSString *coverimagefile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"coverImageFile"]];
    [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimagefile] placeholderImage:ImageNamed(@"placeholdershipin")];
//    cell.countLabel.text = @"缺少参数";//去掉播放次数

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"index = %ld", indexPath.row);
    
    if ([self.videoArr[indexPath.row][@"filepath"] isKindOfClass:[NSNull class]]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    } else {
        NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"filePath"]];
        self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
        [self presentViewController:self.player animated:YES completion:^{
            [self requestHistory:indexPath ID:self.videoArr[indexPath.row][@"did"]];
            [self requestAddShelfOfVideo:self.videoArr[indexPath.row][@"id"]];
            [self requestStatistics:indexPath ID:self.videoArr[indexPath.row][@"id"]];
            [self noMoreVideos];
        }];
    }
    
}

#pragma mark - MPMoviePlayerPlaybackDidFinishNotification Method

- (void)videoFinished{
    DLog(@"停止播放");
    if (self.player) {
        self.player = nil;
    }
}

- (void)noMoreVideos{
    
    for (UIView *subView in self.player.view.subviews) {
        DLog(@"%@", subView);
        for (UIView *subview in subView.subviews) {
            DLog(@"subView %@", subview);
            for (UIView *subView2 in subview.subviews) {
                for (UIView *subview3 in subView2.subviews) {
                    for (UIView *subview4 in subview3.subviews) {
                        for (UIView *subview5 in subview4.subviews) {
                            if ([subview5 isKindOfClass:[UIButton class]]) {
                                DLog(@"%@", subview5);
                                if (subview5.frame.size.width == 32) {
                                    UIButton *button = (UIButton *)subview5;
                                    [button removeTarget:nil
                                                  action:NULL
                                        forControlEvents:UIControlEventAllEvents];
                                    [button initWithBlock:^(id obj) {
                                        [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
                                    } for:UIControlEventTouchUpInside];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - data request

/** 推荐视频 */
- (void)requestVideo:(UIView *)view{
    if ([view isKindOfClass:[MJRefreshNormalHeader class]]) {
        self.pageIndex = 1;
        [self.videoArr removeAllObjects];
    } else {
        self.pageIndex += 1;
    }
    NSString *URL = [NSString stringWithFormat:KgetVideoByClick, KHostAddress, KOrganizationID, @(self.pageIndex), @"", @"", @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
    
            
            [self.videoArr addObjectsFromArray:responseObject[@"data"][@"items"]];
            [self.videoTableView reloadData];
        } else {
//            [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
        }
        
        [self.videoTableView.mj_header endRefreshing];
        [self.videoTableView.mj_footer endRefreshing];
        
    } failure:^(NSError *error) {
        DLog(@"%@", error);
        [self.videoTableView.mj_header endRefreshing];
        [self.videoTableView.mj_footer endRefreshing];
    }];
}

/** 添加浏览历史(视频) */
- (void)requestHistory:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(2), ID];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

/** 视频添加到书架 */
- (void)requestAddShelfOfVideo:(NSString *)ID{
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddShelf, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加书架成功");
            } else {
                DLog(@"添加书架失败");
            }
            
            
        } failure:^(NSError *error) {
            DLog(@"添加书架失败");
        }];
    }
}

@end
